/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.client.plugin;

import java.io.StringWriter;
import java.util.Collection;

import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.edi.Constant;
import com.edi.db.table.ColumnCell;
import com.edi.db.table.RowEntity;
import com.edi.db.table.TableEntity;

public class CommonPluginResult<T> extends PluginResult<T> {
	@Override
	public Element getAnswerXML() throws Exception {
		Element resultE = DocumentHelper.createElement("result");
		resultE.addElement("state").setText(this.state);
		if (StringUtils.isBlank(this.dsName) == true)
			resultE.addElement("dsName");
		else
			resultE.addElement("dsName").setText(this.dsName);

		Element errorInfoE = resultE.addElement("errorInfo");
		if (!StringUtils.isBlank(this.errorInfo))
			errorInfoE.addCDATA(this.errorInfo);
		Element tableE = resultE.addElement("table");
		Element objectE = resultE.addElement("object");
		System.out.println("------------------------errorInfo:"+this.errorInfo);

		if (state.equals(Constant.EXEC_STATE_ERROR))
			return resultE;

		if (result instanceof TableEntity) { // 如果是tableEntity，则加载table信息
			//			resultE = DocumentHelper.createElement("result");    //此处不需要再重新产生“result” ，否则出错，---cya 2009-3-23
			TableEntity returnTable = (TableEntity) result;
			while (returnTable.hasNextRow()) {
				Element rowE = tableE.addElement("row");
				RowEntity row = returnTable.next();
				Collection<ColumnCell> cells = row.getColumnCells().values();
				for (ColumnCell cell : cells) {
					Element cellE = rowE.addElement(cell.getFieldName());
					if (cell.getFieldValue() != null) {
						cellE.addCDATA(cell.getFieldValue().toString());
					}
				}
			}
		} else if (result instanceof Element) { //本身即是Element
			Element e = (Element) result;
			if (e.getName().equals("table"))
				tableE = e;
			else if (e.getName().equals("object"))
				objectE = e;
			else
				resultE.add(objectE);
		} else { // 非tableEntity信息，则返回Object2XML内容
			Element e = object2XML();
			if (e != null)
				objectE.add(e);
		}

		return resultE;
	}

	/**
	 * 把对象编译为xml对象
	 * 
	 * @return
	 * @throws Exception
	 */
	private Element object2XML() throws Exception {
		if (result == null)
			return null;

		StringWriter outputWriter = new StringWriter();
		BeanWriter beanWriter = new BeanWriter(outputWriter);

		beanWriter.getXMLIntrospector().getConfiguration()
				.setAttributesForPrimitives(false);
		beanWriter.getBindingConfiguration().setMapIDs(false);
		beanWriter.enablePrettyPrint();
		beanWriter.setWriteEmptyElements(false);
		beanWriter.setEndTagForEmptyElement(false);

		beanWriter.write(result);

		String xml = outputWriter.toString();
		outputWriter.close();

		Document root = DocumentHelper.parseText(xml);
		return root.getRootElement();
	}

}
